package com.zhigongtech.core.web.jwt;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JwtUtil {
	
	private static double EXPIRE_MINUTE_TIME;
	
	private static final String TRANS_ACCOUNT="account";
	
	@Value("${server.session.timeout:30}")
    private double serverTimeout;
	
	@PostConstruct
	public void initExpTime() {
		EXPIRE_MINUTE_TIME = this.serverTimeout;
		log.info("initialization expire time ："+EXPIRE_MINUTE_TIME+" (MINUTE)");
	}
	
	/**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String username, String secret) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim(TRANS_ACCOUNT, username)
                    .build();
            //效验TOKEN
//            DecodedJWT jwt = verifier.verify(token);
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
        	exception.printStackTrace();
            return false;
        }
    }
 
    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getAccount(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(TRANS_ACCOUNT).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    public static Date getExpireDate(String token) {
    	try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
 
    /**
     * 生成签名,5min后过期
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(String username, String secret) {
    	Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, Double.valueOf(EXPIRE_MINUTE_TIME*60).intValue());
        Date date = cal.getTime(); //new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim(TRANS_ACCOUNT, username)
                .withExpiresAt(date)
                .sign(algorithm);
 
    }
}
